<template>
  <div>
    <div class="app-container">
      <el-form
        :model="queryParams"
        ref="queryRef"
        v-show="showSearch"
        :inline="true"
        label-width="68px"
      >
        <el-form-item label="回收编码" prop="recycleCode">
          <el-input
            v-model="queryParams.recycleCode"
            placeholder="请输入"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="商品品牌" prop="brand">
          <el-select
            v-model="queryParams.brand"
            filterable
            reserve-keyword
            clearable
            style="width: 230px"
            allow-create
            default-first-option
            placeholder="请选择品牌"
          >
            <el-option
              v-for="item in item_brand"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="商品编码" prop="ref">
          <el-input
            v-model="queryParams.ref"
            placeholder="请输入"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="商品型号" prop="model">
          <el-input
            v-model="queryParams.model"
            placeholder="请输入"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="商品状态" prop="itemStatus">
          <el-select
            v-model="queryParams.itemStatus"
            placeholder="状态"
            style="width: 90px"
            clearable
          >
            <el-option
              v-for="i in item_status"
              :key="i.value"
              :label="i.label"
              :value="i.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="回收价格" prop="recyclePrice">
          <el-input
            v-model="queryParams.recyclePrice"
            placeholder="请输入"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="回收人" prop="recyclePersonId">
          <el-select
            v-model="queryParams.recyclePersonId"
            filterable
            remote
            reserve-keyword
            placeholder="请选择"
            :remote-method="getUserOption"
            :loading="userLoading"
            style="width: 200px"
          >
            <el-option
              v-for="item in userOptions"
              :key="item.value"
              :label="item.label"
              :value="item.nickName"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="打款时间">
          <el-date-picker
            v-model="RecycleTime"
            value-format="YYYY-MM-DD"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            style="width: 230px"
            end-placeholder="结束日期"
            :shortcuts="shortcuts"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="维修人" prop="maintenancePersonId">
          <el-select
            v-model="queryParams.maintenancePersonId"
            filterable
            remote
            reserve-keyword
            placeholder="请选择维修人"
            :remote-method="getUserOption"
            :loading="userLoading"
            style="width: 200px"
          >
            <el-option
              v-for="item in userOptions"
              :key="item.value"
              :label="item.label"
              :value="item.nickName"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="维修日期">
          <el-date-picker
            v-model="maintenanceTime"
            value-format="YYYY-MM-DD"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :shortcuts="shortcuts"
          ></el-date-picker>
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            icon="Search"
            @click="handleQuery"
            v-hasPermi="['erp:skesItemMaintenance:query']"
            >搜索</el-button
          >
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['erp:skesItemMaintenance:add']"
            >维修登记</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="Delete"
            @click="handleDelete"
            :disabled="!selectionData.length"
            v-hasPermi="['erp:skesItemMaintenance:remove']"
            >删除</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['erp:skesItemMaintenance:export']"
            >导出</el-button
          >
        </el-col>
        <right-toolbar
          v-model:showSearch="showSearch"
          @queryTable="getList"
        ></right-toolbar>
      </el-row>
      <el-table
        v-loading="loading"
        :data="dataList"
        height="60vh"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="回收编码" prop="recycleCode" align="center" />
        <el-table-column label="商品编码" prop="ref" align="center" />
        <el-table-column label="商品型号" prop="model" align="center" />
        <el-table-column label="品牌" prop="brand" align="center">
          <template #default="scope">
            <dict-tag
              v-if="scope.row.brand"
              :options="item_brand"
              :value="scope.row.brand"
            />
            <span v-else>{{ scope.row.brandName }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="商品正面图"
          prop="watchImageUrl"
          align="center"
          width="110"
        >
          <template #default="scope">
            <div style="display: flex; align-items: center; width: 50px">
              <el-image
                :src="scope.row.watchImageUrl"
                :preview-src-list="[scope.row.watchImageUrl]"
                preview-teleported
              />
            </div>
          </template>
        </el-table-column>
        <el-table-column
          label="商品背面图"
          prop="watchImageUrlBack"
          align="center"
          width="110"
        >
          <template #default="scope">
            <div style="display: flex; align-items: center; width: 50px">
              <el-image
                :src="scope.row.watchImageUrlBack"
                :preview-src-list="[scope.row.watchImageUrlBack]"
                preview-teleported
              />
            </div>
          </template>
        </el-table-column>
        <el-table-column label="回收价格" prop="recyclePrice" align="center" />
        <el-table-column
          label="打款时间"
          prop="paymentTime"
          align="center"
          width="100"
        />
        <el-table-column label="商品状态" prop="itemStatus" align="center">
          <template #default="scope">
            <dict-tag :options="item_status" :value="scope.row.itemStatus" />
          </template>
        </el-table-column>
        <el-table-column
          label="维修日期"
          prop="maintenanceTime"
          align="center"
          width="100"
        />
        <el-table-column
          label="维修类型"
          prop="maintenanceType"
          align="center"
        />
        <el-table-column
          label="维修项目"
          prop="maintenanceProject"
          align="center"
        />

        <el-table-column
          label="故障描述"
          prop="maintenanceDesc"
          align="center"
        />
        <el-table-column
          label="维修人"
          prop="maintenancePerson"
          align="center"
        />
        <el-table-column
          label="维修工费"
          prop="maintenanceCost"
          :show-overflow-tooltip="true"
          align="center"
        />
        <el-table-column
          label="维修提成"
          prop="maintenanceCommissions"
          align="center"
        />
        <el-table-column label="备注" prop="remark" align="center" />
        <el-table-column
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
        >
          <template #default="scope">
            <el-tooltip
              content="修改"
              placement="top"
              v-if="scope.row.roleId !== 1"
            >
              <el-button
                link
                type="primary"
                icon="Edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['erp:skesItemMaintenance:edit']"
              ></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button
                link
                type="primary"
                icon="Delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['erp:skesItemMaintenance:remove']"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <div class="footer-msg">
        <p>
          <i class="el-icon-warning blue-text"></i>
          数量总和:
          <span class="blue-text">{{ summaryInfo.sumCount || "N/A" }}</span>
        </p>
        <p>
          维修成本总金额:<span class="blue-text">{{
            summaryInfo.sumMaintenanceCost || "N/A"
          }}</span>
        </p>
        <p>
          维修提成总金额:<span class="blue-text">{{
            summaryInfo.sumMaintenanceComissions || "N/A"
          }}</span>
        </p>
      </div>
      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </div>
    <add
      v-model:visible="addParams.visible"
      :params="addParams"
      :options="payment_status"
      @refresh="getList"
    />
  </div>
</template>
<script setup name="Maintenance_register">
import { listTable, delRegister } from "@/api/maintenance/register";
import { optionSelect } from "@/api/system/skesItem";
import { userOptionSelect } from "@/api/system/user";
import Add from "./add.vue";
const { proxy } = getCurrentInstance();
const dataList = ref([]);
const selectionData = ref([]);
const total = ref(0);
const loading = ref(true);
const showSearch = ref(true);
const summaryInfo = ref({});

const maintenanceTime = ref([]);
const { payment_status } = proxy.useDict("payment_status");
const { item_brand, item_status } = proxy.useDict("item_brand", "item_status");

const addParams = ref({
  type: "add",
  visible: false,
  id: undefined,
});
const shortcuts = [
  {
    text: "最近一周",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
      return [start, end];
    },
  },
  {
    text: "最近一个月",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
      return [start, end];
    },
  },
  {
    text: "最近三个月",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
      return [start, end];
    },
  },
];
const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    ref: undefined,
    model: undefined,
    itemStatus: undefined,
    recyclePrice: undefined,
    recyclePerson: undefined,
    maintenanceCode: undefined,
    maintenancePerson: undefined,
    recycleCode: undefined,
    brand: undefined,
  },
});
const { queryParams, form, rules } = toRefs(data);

/** 用户下拉框 */
const userLoading = ref(false);
const userOptions = ref([]);
async function getUserOption(query) {
  if (query) {
    userLoading.value = true;
    const { data } = await userOptionSelect({ queryKey: query });
    userOptions.value = data.map((i) => {
      const { userId, nickName, userName } = i;
      return {
        value: i.userId,
        label: `${userId},${nickName},${userName}`,
        nickName,
      };
    });
    userLoading.value = false;
  }
}
getUserOption(" ");
/** 查询列表 */
const RecycleTime = ref([]);
function getList() {
  loading.value = true;
  const [beginRecycleTime, endRecycleTime] = RecycleTime.value;
  const [beginMaintenanceTime, endMaintenanceTime] = maintenanceTime.value;
  listTable({
    ...queryParams.value,
    params: {
      beginRecycleTime,
      endRecycleTime,
      beginMaintenanceTime,
      endMaintenanceTime,
    },
  }).then((response) => {
    dataList.value = response.rows;
    summaryInfo.value = { ...response, rows: undefined };
    total.value = response.total;
    loading.value = false;
  });
}
/** 搜索按钮操作 */
function handleQuery() {
  queryParams.pageNum = 1;
  getList();
}
/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  maintenanceTime.value = [];
  RecycleTime.value = [];
  handleQuery();
}
/** 导出按钮操作 */
function handleExport() {
  const [beginRecycleTime, endRecycleTime] = RecycleTime.value;
  const [beginMaintenanceTime, endMaintenanceTime] = maintenanceTime.value;
  proxy.download(
    "maintenance/register/export",
    {
      ...queryParams.value,
      params: {
        beginRecycleTime,
        endRecycleTime,
        beginMaintenanceTime,
        endMaintenanceTime,
      },
    },
    `maintenance_${new Date().getTime()}.xlsx`
  );
}
/** 删除按钮操作 */
function handleDelete(row) {
  let ids = [],
    brands = [];
  if (row.id) {
    ids = row.id;
    brands = row.brand;
  } else {
    selectionData.value.forEach((i) => {
      ids.push(i.id);
      brands.push(i.brand);
    });
    ids = ids.join(",");
    brands = brands.join(",");
  }
  proxy.$modal
    .confirm('是否确认删除商品"' + brands + '"的数据项?')
    .then(function () {
      return delRegister(ids);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}
/** 添加商品*/
function handleAdd() {
  /** 添加商品*/
  if (!selectionData.value.length) {
    proxy.$modal.msgError("请选择维修登记的商品");
    return;
  } else if (selectionData.value.length > 1) {
    proxy.$modal.msgError("请只选择一个商品");
    return;
  }
  addParams.value = {
    type: "add",
    visible: true,
    id: selectionData.value[0].id,
  };
}
/** 修改商品*/
function handleUpdate(row) {
  addParams.value = {
    type: "edit",
    visible: true,
    id: row.itemId,
  };
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  selectionData.value = selection.map((i) => ({
    id: i.itemId,
    brand: i.brand,
  }));
}
getList();
</script>
